/**
* 基础管理 库存管理
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>库存管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="formInline.productName" placeholder="输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-input size="small" v-model="formInline.productCode" placeholder="输入商品编号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button  size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
        <el-button  size="small" type="primary" icon="el-icon-plus" @click="inStore()">入库</el-button>
        <el-button  size="small" type="primary" icon="el-icon-minus" @click="outStore()">出库</el-button>
<!--        <el-button  size="small" type="primary" icon="el-icon-upload2" @click="upLoad()">批量导入</el-button>-->
        <el-button  size="small" type="primary" icon="el-icon-upload2" @click="downLoad()">导出Excel</el-button>
        <el-button  v-if="flag" size="small" type="primary" icon="el-icon-upload2" @click="upLoad()">传至数据库</el-button>
      </el-form-item>
    </el-form>

    <el-upload
      action="/上传文件的接口"
      :on-change="onChange"
      :auto-upload="false"
      :show-file-list="false"
      accept=".xls, .xlsx"
    >
      <el-button size="small" type="primary" icon="el-icon-download">导入Excel</el-button>
    </el-upload>

    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中"
              style="width: 100%;"  :row-style="isRed" >
      <el-table-column align="center" type="index" width="50"></el-table-column>
      <el-table-column sortable prop="name" label="商品名称" width="100" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column sortable prop="location" label="库房地址" width="120" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column sortable prop="inventorySum" label="库存入库总量" width="120" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column sortable prop="inventoryRemove" label="库存出库总量" width="120" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column sortable prop="inventory" label="商品现库存量" width="100" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column sortable prop="alarmValue" label="商品警告值" width="100" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column sortable prop="addUser" label="创建用户" width="100" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column sortable prop="addTime" label="创建时间" width="130" show-overflow-tooltip align="center">
        <template slot-scope="scope">
          <div>{{scope.row.addTime|timestampToTime}}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="editUser" label="编辑用户" width="100" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column sortable prop="editTime" label="编辑时间" width="130" show-overflow-tooltip align="center" >
        <template  slot-scope="scope">
          <div>{{scope.row.editTime|timestampToTime}}</div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="250">
        <template slot-scope="scope">
          <el-button  size="mini" @click="setWarning(scope.$index, scope.row)">设置告警</el-button>
          <el-button  size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteInventory(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>


    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="40%" @click="closeDialog('editForm')">
      <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">

        <el-row>
          <el-col :span="12">
            <el-form-item label="编号" prop="id">
              <el-input size="small" v-model="editForm.id" auto-complete="off" placeholder="请输入编号" disabled="true"></el-input>
            </el-form-item>

            <el-form-item label="名称" prop="name">
              <el-input size="small" v-model="editForm.name" auto-complete="off" placeholder="请输入商品名称"></el-input>
            </el-form-item>

            <el-form-item label="库存入库总量" prop="inventorySum">
              <el-input size="small" v-model="editForm.inventorySum" auto-complete="off" placeholder="库存入库总量"  disabled="true"></el-input>
            </el-form-item>

            <el-form-item label="库存地址" prop="location">
              <el-input size="small" v-model="editForm.location" auto-complete="off" placeholder="请输入库存地址"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">

            <el-form-item label="部门" prop="unit">
              <el-select size="small" v-model="editForm.unit" placeholder="请选择部门">
                <el-option selected label="请选择" value=""></el-option>
                <el-option v-for="parm in dept" :key="parm.name" :label="parm.name" :value="parm.id"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="库存总量" prop="inventory">
              <el-input size="small" v-model="editForm.inventory" placeholder="请输入库存总量" auto-complete="off"></el-input>
            </el-form-item>

            <el-form-item label="库存出库总量" prop="inventoryRemove">
              <el-input size="small" v-model="editForm.inventoryRemove" auto-complete="off" placeholder="库存出库总量" disabled="true"></el-input>
            </el-form-item>

            <el-form-item label="警告值" prop="alarmValue">
              <el-input size="small" v-model="editForm.alarmValue" auto-complete="off" placeholder="请输入警告值"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('editForm')">取消</el-button>
        <el-button  size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>


    <!-- 入库界面 -->
    <el-dialog  :title="IninventoryTitle" :visible.sync="editFormInVisible" width="67%" @click="closeDialog('ScanDataIn')"
               @input="Scan">
      <div style="text-align:center;vertical-align:middle;"><!--<input type="text" ></div>-->
      <el-input
        :clearable="true" @keyup.enter.native="fill()"
        ref="gain"
        style="width: 450px;"
        placeholder="请扫描物品条形码"
        v-model="codeValue"        ><!--:autofocus="true"-->
      </el-input>
      </div>
      <el-table size="small" :data="ScanData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;" >
        <el-table-column sortable prop="id" label="商品编号" width="100" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column sortable prop="name" label="商品名称" width="200" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column sortable prop="inventory" label="商品现库存量" width="150" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column sortable prop="alarmValue" label="商品警告值" width="150" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column sortable prop="addUser" label="创建用户" width="150" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column sortable prop="addTime" label="创建时间" width="200" show-overflow-tooltip align="center">
          <template slot-scope="scope">
          <div>{{scope.row.addTime|timestampToTime}}</div>
        </template>
        </el-table-column>
<!--        <el-table-column sortable prop="Value" label="入库数量" width="000" show-overflow-tooltip align="center"></el-table-column>-->
        <el-table-column prop="value" label="入库数量" width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-input v-model="scope.row.value" @change="funtion" @input='getNum' placeholder="请输入入库数量" class="group-inp"></el-input>
        </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('gain')">取消</el-button>
        <el-button  size="small" type="primary" :loading="loading" class="title" @click="submitFormIn('ScanData')">入库</el-button>
        </div>
    </el-dialog>

    <!-- 出库界面 -->
    <el-dialog :autofocus="true" :title="OutinventoryTitle" :visible.sync="editFormOutVisible" width="67%" @click="closeDialog('ScanDataOut')"
               @input="Scan">

      <div style="text-align:center;vertical-align:middle;"><!--<input type="text" ></div>-->
        <el-input
          :clearable="true" @keyup.enter.native="fill()"
          ref="gain"
          style="width: 450px;"
          placeholder="请扫描物品条形码"
          v-model="codeValue" >  <!--:autofocus="autofocus"-->
        </el-input>
      </div>

      <el-table size="small" :data="ScanData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;" >
        <el-table-column sortable prop="id" label="商品编号" width="100" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column sortable prop="name" label="商品名称" width="200" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column sortable prop="inventory" label="商品现库存量" width="150" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column sortable prop="alarmValue" label="商品警告值" width="150" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column sortable prop="addUser" label="创建用户" width="150" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column sortable prop="addTime" label="创建时间" width="200" show-overflow-tooltip align="center">
          <template slot-scope="scope">
          <div>{{scope.row.addTime|timestampToTime}}</div>
        </template>
        </el-table-column>
<!--        <el-table-column sortable prop="outValue" label="出库数量" width="100" show-overflow-tooltip align="center"></el-table-column>-->
        <el-table-column prop="value" label="出库数量" width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.value" @change="funtion" @input='getNum' placeholder="请输入出库数量" class="group-inp">

             </el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('gain')">取消</el-button>
        <el-button  size="small" type="primary" :loading="loading" class="title" @click="submitFormOut('ScanData')">出库</el-button>
      </div>
    </el-dialog>



</div>
</template>

<script>
  import {

    getInventory,
    inInventory,
    inventoryDept,
    outInventory,
    removeInventory,
    saveInvatory, showScanData,
    up
  } from '../../api/payMG'
  import Pagination from '../../components/Pagination'
  import {lert} from "../../api/axiosFun";
  import {formatExcelDate} from "../../utils/util";
  import {export_json_to_excel} from "../../excel/Export2Excel";

  export default {
    data() {
      return {
        // 实例化一个音频播放器对象
        audio: new Audio(),
        audio1: require('../../assets/audio/audio1.mp3'),
        audio2: require('../../assets/audio/audio2.mp3'),

        flag: false,
        fileData:'',
        getNums: "",
        code: '',
        codeValue:'',
        nextCode: '',
        lastCode: '',
        lastTime: '',
        nextTime: '',
        IninventoryTitle: '入库',
        OutinventoryTitle: '出库',
        ScanData: [],
        loading: false, //是显示加载
        warningValue: '',
        editFormVisible: false, //控制编辑页面显示与隐藏
        editFormInVisible:false, //控制出入库页面显示与隐藏
        editFormOutVisible:false, //控制出入库页面显示与隐藏
        title: '添加',
        dept: [],
        editForm: {
          issave: false,
          id: '',
          name: '',
          inventory: 1,
          inventorySum: '',
          inventoryRemove: '',
          unit: '',
          location: '',
          alarmValue: '',
          username: localStorage.getItem('username')
    },
        // rules表单验证
        rules: {
          id: [{ required: false, message: '请输入商品id', trigger: 'blur' }],
          name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          inventory: [{ required: true, message: '请输入现库存总量', trigger: 'blur' }],
          inventorySum: [
            { required: false, message: '请输入入库存总量', trigger: 'blur' }
          ],
          inventoryRemove: [{ required: false, message: '请输入出库存总量', trigger: 'blur' }],
          unit: [
            { required: true, message: '请选择部门', trigger: 'blur' }
          ],
          location: [
            { required: true, message: '请输入库存地址', trigger: 'blur' }
          ],
          alarmValue: [
            { required: true, message: '请输入告警值', trigger: 'blur' }
          ],
        },
        formInline: {
          productName:'',
          page: 1,
          limit: 10,
          productCode: '',
        },
        listData: [], //用户数据
        // 分页参数
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },
        selectData: []
      }
    },
    // 注册组件
    components: {
      Pagination
    },
    /**
     * 数据发生改变
     */

    /**
     * 创建完毕
     */
    created() {
      this.getDept()


      window.document.onkeypress = (e) => {
      if (window.event) { // IE
        this.nextCode = e.keyCode
      } else if (e.which) { // Netscape/Firefox/Opera
        this.nextCode = e.which
      }
      // console.log(e.which)
      // console.log(this.row)
      console.log("-------------")
      if (e.which === 13) { // 键盘回车事件
        console.log(this.code)
        console.log("条形码长度："+this.code.length)
        if(this.code.length == 0){
          console.log(this.code)
          this.parseQRCode(this.code) // 获取到扫码枪输入的内容，做别的操作
          this.lastCode = ''
          this.lastTime = ''
          return
        }//新加的需要删除掉的
        if (this.code.length < 3) return // 扫码枪的速度很快，手动输入的时间不会让code的长度大于2，所以这里不会对扫码枪有效
        console.log('扫码结束。')
        console.log('条形码：', this.code)
        this.parseQRCode(this.code) // 获取到扫码枪输入的内容，做别的操作
        this.lastCode = ''
        this.lastTime = ''
        return
      }

      this.nextTime = new Date().getTime()
      if (!this.lastTime && !this.lastCode) {
        this.code = '' // 清空上次的条形码
        this.code += e.key
        console.log('扫码开始---', this.code)
      }
      if (this.lastCode && this.lastTime && this.nextTime - this.lastTime > 500) { // 当扫码前有keypress事件时,防止首字缺失
        this.code = e.key
        console.log('防止首字缺失。。。', this.code)
      } else if (this.lastCode && this.lastTime) {
        this.code += e.key
        console.log('扫码中。。。', this.code)
      }
      this.lastCode = this.nextCode
      this.lastTime = this.nextTime
    }
 
      this.getdata(this.formInline)
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      //获取焦点
      autofocus() {
        this.$nextTick(() => {
          this.$refs.gain.focus()

        }, 100)
      },

      //获取部门信息
      getDept() {
        inventoryDept()
        .then(res=>{
          lert(res)
          this.dept = JSON.parse(res.data);
        }).catch(err => {
          this.$message.error('部门信息获取失败，请稍后再试！')
        })
      },
      // 获取所有库存列表
      getdata(parameter) {
        console.log(this.codeValue)
        this.loading = true
        getInventory(parameter)
          .then(res => {
            this.loading = false
            if (res.success == false) {
              this.$message({
                type: 'info',
                message: res.msg
              })
            } else {
              this.loading = false
              var result = JSON.parse(res.data);
              this.listData =result.records
              // 分页赋值
              this.pageparm.currentPage = result.current
              this.pageparm.pageSize = result.size
              this.pageparm.total = result.total
              this.$message.success(res.msg)
            }
          })
          .catch(err => {
            this.loading = false
            this.$message.error('库存信息加载失败，请稍后再试！')
          })
      },
      getNum(value){
        this.getNums = value
      },
      funtion(row) {
        this.ScanData.value=row.value
      },

      //设置告警
      setWarning(index, row) {
        this.selectData.push(row)
        console.log(this.selectData)
      },

      //动态设置每行的颜色
      isRed({row}) {
        const checkIdlist = this.selectData.map((item) => item.id)
        if (row.alarmValue > row.inventory) {
          checkIdlist.push(row.id)
        }
        if (checkIdlist.includes(row.id)) {
          return{
            backgroundColor: "#e6a23c",
            color: "red"
          };
        }
      },

      //显示编辑界面
      handleEdit: function(index, row) {
        this.editFormVisible = true
        if (row != undefined && row != 'undefined') {
          this.title = '修改'
          this.editForm.issave=false
          this.editForm.id = row.id
          this.editForm.name = row.name
          this.editForm.inventory = row.inventory
          this.editForm.inventorySum = row.inventorySum
          this.editForm.inventoryRemove = row.inventoryRemove
          this.editForm.unit = row.unit
          this.editForm.location = row.location
          this.editForm.alarmValue = row.alarmValue
        } else {
          this.title = '添加'
          this.editForm.issave=true
          this.editForm.id = ""
          this.editForm.name = ""
          this.editForm.inventory = ""
          this.editForm.inventorySum = ""
          this.editForm.inventoryRemove = ""
          this.editForm.unit = ""
          this.editForm.location = ""
          this.editForm.alarmValue = ""
        }
      },
      // 分页插件事件
      callFather(parm) {
        this.formInline.page = parm.currentPage
        this.formInline.limit = parm.pageSize
        this.getdata(this.formInline)
      },
      // 搜索事件
      search() {
        this.getdata(this.formInline)
      },

      // 编辑、增加页面保存方法
      submitForm(editData) {
        this.$refs[editData].validate(valid => {
          if (valid) {
            saveInvatory(this.editForm)
              .then(res => {
                lert(res);
                this.editFormVisible = false
                this.loading = false
                if (res.success) {
                  this.getdata(this.formInline)
                  this.$message({
                    type: 'success',
                    message: '库存信息保存成功！'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.editFormVisible = false
                this.loading = false
                this.$message.error('库存信息保存失败，请稍后再试！')
              })
          } else {
            return false
          }
        })
      },
      // 删除库存信息
      deleteInventory(index, row) {
        this.$confirm('确定要删除吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            removeInventory(row.id)
              .then(res => {
                lert(res);
                if (res.success) {
                  this.$message({
                    type: 'success',
                    message: '库存信息已删除!'
                  })
                  this.getdata(this.formInline)
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.loading = false
                this.$message.error('库存信息删除失败，请稍后再试！')
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      },
      //入库
      inStore(){
        this.editFormInVisible=true
        this.autofocus()
      },
      submitFormIn(){
        let params={
          ids:[],
          values:[],
          names:[]
        }
        
        for (let index = 0; index < this.ScanData.length; index++){
          params.ids.push(this.ScanData[index].id)
          if(index!=this.ScanData.length-1){
            params.ids.push(',')
          }
          params.values.push(this.ScanData[index].value)
          if(index!=this.ScanData.length-1){
            params.values.push(',')
          }
          params.names.push(this.ScanData[index].name)
          if(index!=this.ScanData.length-1){
            params.names.push(',')
          }
        }

        // var params=JSON.stringify(this.ScanData)
        console.log(params)
        inInventory(params)
          .then(res=>{
            if(res.success) {
              // 开启自动播放
              this.audio.autoplay = true;
              this.audio.src = this.audio1;
              this.ScanData = []
              this.$message.success(res.msg)
              this.editFormInVisible = false
              this.getdata(this.formInline)
              
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
          .catch(err => {
            this.$message.error('入库失败，请稍后再试！')
          })
          this.ScanData=[]
      },
      //出库
      outStore(){
        this.editFormOutVisible=true
        this.autofocus()
      },
      //出库
      submitFormOut() {
        let params={
          ids:[],
          values:[],
          names:[]
        }
        
        for (let index = 0; index < this.ScanData.length; index++){
          params.ids.push(this.ScanData[index].id)
          if(index!=this.ScanData.length-1){
            params.ids.push(',')
          }
          params.values.push(this.ScanData[index].value)
          if(index!=this.ScanData.length-1){
            params.values.push(',')
          }
          params.names.push(this.ScanData[index].name)
          if(index!=this.ScanData.length-1){
            params.names.push(',')
          }
        }
        outInventory(params)
          .then(res=>{
            if(res.success) {
              // 开启自动播放
              this.audio.autoplay = true;
              this.audio.src = this.audio1;

              this.ScanData = []
              this.$message.success(res.msg)
              this.editFormOutVisible = false
              this.getdata(this.formInline)
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
          .catch(err => {
            this.$message.error('出库失败，请稍后再试！')
          })
          this.ScanData=[]
      },
      //扫码
      // Scan() {
      //   window.document.onkeypress = (e) => {
      //     if (window.event) { // IE
      //       this.nextCode = e.keyCode
      //     } else if (e.which) { // Netscape/Firefox/Opera
      //       this.nextCode = e.which
      //     }
      //     // console.log(e.which)
      //     // console.log(this.row)
      //     console.log("-------------")
      //     if (e.which === 13) { // 键盘回车事件
      //       console.log(this.code.length)
      //       if(this.code.length == 0){
      //         console.log(this.code)
      //         this.parseQRCode(this.code) // 获取到扫码枪输入的内容，做别的操作
      //         this.lastCode = ''
      //         this.lastTime = ''
      //         return
      //       }//新加的需要删除掉的
      //       if (this.code.length < 3) return // 扫码枪的速度很快，手动输入的时间不会让code的长度大于2，所以这里不会对扫码枪有效
      //       console.log('扫码结束。')
      //       console.log('条形码：', this.code)
      //       this.parseQRCode(this.code) // 获取到扫码枪输入的内容，做别的操作
      //       this.lastCode = ''
      //       this.lastTime = ''
      //       return
      //     }

      //     this.nextTime = new Date().getTime()
      //     if (!this.lastTime && !this.lastCode) {
      //       this.code = '' // 清空上次的条形码
      //       this.code += e.key
      //       console.log('扫码开始---', this.code)
      //     }
      //     if (this.lastCode && this.lastTime && this.nextTime - this.lastTime > 500) { // 当扫码前有keypress事件时,防止首字缺失
      //       this.code = e.key
      //       console.log('防止首字缺失。。。', this.code)
      //     } else if (this.lastCode && this.lastTime) {
      //       this.code += e.key
      //       console.log('扫码中。。。', this.code)
      //     }
      //     this.lastCode = this.nextCode
      //     this.lastTime = this.nextTime
      //   }
      // },
      //解析信息码
      parseQRCode(code) {
        //这里可以去加一些判断验证码长度的代码
        if (code.length === 0) {
          // 处理自己的逻辑
          console.log('请输入条码！')
          alert("扫描失败,没有码")
        } else {
          console.log("通过条形码请求后端开始")
          let codeParams = {
            codeParam:code
          }
          //这里写请求后端的接口，去获取信息展示在table 中
          showScanData(codeParams)
          .then(res=>{
            if(res.success) {
              console.log(res)
              console.log(JSON.parse(res.data))
              this.ScanData.push(JSON.parse(res.data))
              console.log(this.ScanData)
              this.$message.success(res.msg)
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }

          })
        }
        this.codeValue=code
      },

      //上传数据
      upLoad(){
        for (let i = 0; i < this.listData.length; i++) {
          let parm={
            name: this.listData[i].name,
            location: this.listData[i].location,
            inventorySum: this.listData[i].inventorySum,
            inventoryRemove: this.listData[i].inventoryRemove,
            inventory: this.listData[i].inventory,
            alarmValue: this.listData[i].alarmValue
          }
          up(parm)
            .then(res=>{
              if(res.success) {

                this.$message.success(res.msg)
                this.flag = false
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.$message.error('上传数据失败，请稍后再试！')
            })
        }

      },

      //下载数据(导出为excel)
      downLoad(){
        require.ensure([], () => {
          const fieldName = ["商品名称", "库房地址", "库房入库总量","库房出库总量","商品现库存量","商品警告值","创建用户","创建时间","编辑用户","编辑时间"];
          const filterVal = ["name", "location", "inventorySum","inventoryRemove","inventory","alarmValue","addUser","addTime","editUser","editTime"];
          const data = this.listData.map(v => filterVal.map(j => v[j]));
          export_json_to_excel(fieldName, data, "库存信息表"+new Date());
        })

      },
      // ----------以下为导入Excel数据功能--------------
      // 文件选择回调
      onChange(file) {
        this.fileData = file; // 保存当前选择文件
        this.readExcel(); // 调用读取数据的方法
      },
      // 读取数据
      readExcel() {
        let that = this;
        const files = that.fileData;
        if (!files) {
          return false;
        } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
          this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
          return false;
        }
        const fileReader = new FileReader();
        fileReader.onload = ev => {
          try {
            const data = ev.target.result;
            const workbook = this.$XLSX.read(data, {
              type: "binary"
            });

            if (workbook.SheetNames.length >= 1) {
              this.$message({
                message: "导入数据表格成功",
                showClose: true,
                type: "success"
              });
            }
            const wsname = workbook.SheetNames[0]; //取第一张表
            const ws = this.$XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
            for (var i = 0; i < ws.length; i++) {
              var sheetData = {
                // 键名为绑定 el 表格的关键字，值则是 ws[i][对应表头名]
                name: ws[i]["商品名称"],  //前面是prop 括号里面是label
                location: ws[i]["库房地址"],
                inventorySum: ws[i]["库房入库总量"],
                inventoryRemove: ws[i]["库房出库总量"],
                inventory: ws[i]["商品现库存量"],
                alarmValue: ws[i]["商品警告值"],
                addUser: ws[i]["创建用户"],
                addTime: formatExcelDate(ws[i]["创建时间"],"-"),
                editUser: ws[i]["编辑用户"],
                editTime: formatExcelDate(ws[i]["编辑时间"],"-"),

              }
              that.listData.push(sheetData);

            }
            this.$refs.upload.value = "";
          } catch (e) {
            return false;
          }
        };
        // 如果为原生 input 则应是 files[0]
        fileReader.readAsBinaryString(files.raw);
        this.flag = true;
      },

      // 关闭编辑、增加弹出框
      closeDialog(formName) {
        this.editFormVisible = false
        this.editFormInVisible = false
        this.editFormOutVisible = false;
        this.codeValue=''
        this.$refs[formName].resetFields()
      }
    }
  }
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }
  .userRole {
    width: 100%;
  }

</style>


